package com.alipay.rebate.shop.scheduler.orderimport;

import com.alipay.rebate.shop.constants.*;
import com.alipay.rebate.shop.dao.mapper.*;
import com.alipay.rebate.shop.helper.JpushHelper;
import com.alipay.rebate.shop.helper.LuckyMoneyHelper;
import com.alipay.rebate.shop.helper.UserHelper;
import com.alipay.rebate.shop.helper.UserIncomeBuilder;
import com.alipay.rebate.shop.model.*;
import com.alipay.rebate.shop.pojo.user.customer.UserCouponRsp;
import com.alipay.rebate.shop.scheduler.AwardGradValue;
import com.alipay.rebate.shop.utils.DateUtil;
import com.alipay.rebate.shop.utils.DecimalUtil;
import com.alipay.rebate.shop.utils.ListUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public abstract class AbstractJdAndPddOrdersImport {

    private Logger logger = LoggerFactory.getLogger(AbstractJdAndPddOrdersImport.class);

    @Resource
    TaskSettingsMapper taskSettingsMapper;
    @Resource
    UserIncomeMapper userIncomeMapper;
    @Resource
    UserHelper userHelper;
    @Resource
    CommissionFreezeLevelSettingsMapper commissionFreezeLevelSettingsMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    InviteSettingsMapper inviteSettingsMapper;
    @Resource
    JpushHelper jpushHelper;
    @Resource
    CouponGetRecordMapper couponGetRecordMapper;
    @Resource
    LuckyMoneyHelper luckyMoneyHelper;
    @Resource
    UserGradeMapper userGradeMapper;
    @Resource
    CommissionLevelSettingsMapper commissionLevelSettingsMapper;
    @Resource
    ActivityBrowseProductMapper activityBrowseProductMapper;
    @Resource
    ActivityProductMapper activityProductMapper;
    @Resource
    OrderActivityRecordMapper orderActivityRecordMapper;

    Gson gson = new Gson();

    //判断是否是新用户
    protected void checkNewUser(Long userId,Integer orderStatus){
        logger.debug("capNew and userId is : {},{}",orderStatus,userId);
        //若订单到了结算状态
        if (orderStatus == PddOrdersConstant.PDD_ACCOUNTING_STATUS || orderStatus == JdOrdersConstant.JD_ACCOUNTING_STATUS){
            // 获取新人用户奖励配置
            TaskSettings taskSettings = taskSettingsMapper.selectUseSettingsBySubType(
                    TaskSettingsConstant.FIRST_ORDER
            );
            logger.debug("taskSettings is : {}",taskSettings);
            // 进行新人用户奖励
            if(taskSettings != null) {
                UserIncome userIncome = UserIncomeBuilder.buildNotOrdersRelateUserIncome(
                        UserIncomeConstant.FIRST_DONE_ORDER_AWARD_TYPE,
                        UserIncomeConstant.UIT_AWARD_TYPE,
                        Long.valueOf(taskSettings.getAwardNum()),
                        userId
                );
                //往用户收益表添加记录
                userIncomeMapper.insertSelective(userIncome);
                userHelper.pluUserVirtualMoneyByType(taskSettings,userId);
            }
        }
    }

    //获取佣金配置
    protected CommissionFreezeLevelSettings getFreezeSettingsByMoney(BigDecimal money,Integer type){
        List<CommissionFreezeLevelSettings> settingsList =
                commissionFreezeLevelSettingsMapper.selectByBeginAndEnd(money,type);
        if(!ListUtil.isEmptyList(settingsList)){
            return settingsList.get(0);
        }
        return null;
    }

    //拉新奖励
    protected Long checkAndAwardToUser(User user,BigDecimal goodsPrice){
        long awardNum  = 0L ;
        // 如果用户有上级
        if(user.getParentUserId() != null){
            logger.debug("parentUserId is : {}",user.getParentUserId());
            int count = userIncomeMapper.selectInviteIncomeByUserId(user.getParentUserId(),user.getUserId());
            logger.debug("InviteIncome count for parentUserId and userId is :{},{},{}",user.getParentUserId(),user.getUserId(),count);
            // 如果针对当前用户已经奖励过推广人,那么无需再进行奖励,否則繼續獎勵
            if(count <= 0){
                InviteSettings inviteSettings = inviteSettingsMapper.selectByPrimaryKey(1);
                String awardGradJson = inviteSettings.getAwardGradJson();
                String conditonJson = inviteSettings.getConditionJson();
                logger.debug("invite settings is : {}",inviteSettings);
                logger.debug("awardGradJson and conditonJson : {},{}",
                        awardGradJson,conditonJson);
                Type type = new TypeToken<Map<String, AwardGradValue>>() {}.getType();
                Map<String, AwardGradValue> qwardGrad = gson.fromJson(awardGradJson,type);
                BigDecimal consumePrice = new BigDecimal(conditonJson);
                // 如果购买的金额大于设置的金额才算拉新成功
                if(goodsPrice.compareTo(consumePrice) >=0){
                    int currentCount = userIncomeMapper.selectCountByUserIdAndType(user.getParentUserId(),UserIncomeConstant.INVITE_AWAED_TYPE);
                    currentCount = currentCount + 1;
                    logger.debug("currentCount is :{}",currentCount);
                    AwardGradValue range1 = qwardGrad.get("1");
                    AwardGradValue range2 = qwardGrad.get("2");
                    AwardGradValue range3 = qwardGrad.get("3");
                    // 确定奖励范围
                    logger.debug("awardNum is : {}",awardNum);
                    if(currentCount>=range1.getBegin() && currentCount<range1.getEnd()){
                        awardNum = range1.getAward();
                    }
                    if(currentCount>=range2.getBegin() && currentCount<range2.getEnd()){
                        awardNum = range2.getAward();
                    }
                    if(currentCount>=range3.getBegin() && currentCount<range3.getEnd()){
                        awardNum = range3.getAward();
                    }
                    userMapper.plusUserUit(awardNum,user.getParentUserId());
//                    Integer roadType = 1;
//                    UserIncome userIncome = UserIncomeBuilder.buildPddInviteUserIncome(orders,awardNum,user.getParentUserId(),roadType);

                }
            }
        }
        return awardNum;
    }

    // 拉新收益记录
    protected void insertPddOrdersPullNewUserIncome(Object object,Long awardNum,User user){
        if (user.getParentUserId() != null) {
            PddOrders pddOrders = (PddOrders) object;
            Integer roadType = 1;
            UserIncome userIncome = UserIncomeBuilder.buildPddInviteUserIncome(pddOrders, awardNum, user.getParentUserId(), roadType);
            logger.debug("UserIncome is : {}", userIncome);
            userIncomeMapper.insertSelective(userIncome);
        }
    }
    // 拉新收益记录
    protected void insertJdOrdersPullNewUserIncome(Object object,Long awardNum,User user){
        if (user.getParentUserId() != null) {
            JdOrders jdOrders = (JdOrders) object;
            Integer roadType = 1;
            UserIncome userIncome = UserIncomeBuilder.buildJdInviteUserIncome(jdOrders, awardNum, user.getParentUserId(), roadType);
            logger.debug("UserIncome is : {}", userIncome);
            userIncomeMapper.insertSelective(userIncome);
        }
    }

    // 用户订单数加1
    protected void countUserOrdersNum(Long userId){
        if(userId != null){
            logger.debug("plusOrdersNum");
            userMapper.plusOrdersNumByOne(userId);
        }
    }

    protected UserIncome getUserIncomeIdFromList(List<UserIncome> userIncomeList,Long userId){
        logger.debug("userIncomeList is : {}",userIncomeList);
        for(int i = 0 ; i<userIncomeList.size() ; i++){
            Long incomeUserId = userIncomeList.get(i).getUserId();
            if(incomeUserId.equals(userId)){
                return userIncomeList.get(i);
            }
        }
        return null;
    }

    // 增加用户集分宝
    protected void plusUserUit(Long userUit,Long oneLevelUit,Long twoLevelUit, User user){
//        Long userUit = orders.getUserUit();
//        Long oneLevelUit = orders.getOneLevelUserUit();
//        Long twoLevelUit = orders.getTwoLevelUserUit();
        // 如果订单是从付款状态进入结算状态，那么增加用户的收益信息
        plusUserUit(userUit,user.getUserId());
        if (user.getParentUserId() != null){
            User parentUser = userMapper.selectById(user.getParentUserId());
            plusUserUit(oneLevelUit,user.getParentUserId());
            if (parentUser.getParentUserId() != null){
                plusUserUit(twoLevelUit,parentUser.getParentUserId());
            }
        }
    }

    // 先检查是否为空再更新
    private void plusUserUit(Long userUit,Long userId){
        if(userId != null && userUit != null){
            logger.debug("plusUserUit");
            userMapper.plusUserUit(userUit,userId);
            // 推送返利到账消息给用户
            jpushHelper.orderCommissionPush(String.valueOf(userId));
        }
    }

    // 处理失效订单
    protected void handleOverDueOrders(String orderId){
        logger.debug("orverdue status");
        // 查询订单收益列表
        List<UserIncome> userIncomeList = userIncomeMapper
                .selectUserIncomeByOrdersId(orderId);
        logger.debug("userIncomeList is : {}",userIncomeList);
        // 如果用户确实获取了收益
        // 存在收益记录
        if(!ListUtil.isEmptyList(userIncomeList)) {
            for (UserIncome userIncome : userIncomeList) {
                BigDecimal money = userIncome.getMoney();
                long uit = money.multiply(new BigDecimal("100")).longValue();
                // 如果已经转账给用户，那么进行扣款
                if (UserIncomeConstant.IS_PAID == userIncome.getStatus()) {
                    if (uit > 0) {
                        userMapper.plusUserUit(-uit, userIncome.getUserId());
                    }
                }
            }
        }
        // 删除这笔订单的收益记录
        userIncomeMapper.deleteByTradeId(orderId);
    }

    protected Integer getIncomeStatusWhenUpdate(
            UserIncome preIncome,Integer accountStatus){
        // 从付款进入到结算/完成，应该为冻结状态
        if (preIncome.getTkStatus() == accountStatus.longValue()){
            return UserIncomeConstant.FREEZE;
        }
        // 如果先前是冻结状态或者付款状态，那么无需改变状态
        if (UserIncomeConstant.FREEZE == preIncome.getStatus()
        ){
            return UserIncomeConstant.FREEZE;
        }
        return 2;
    }

    //红包奖励
    protected void giveLuckyMoney(User user){
        List<UserCouponRsp> userCouponRsps = couponGetRecordMapper.selectCouponDetailByUserId(user.getUserId());
        luckyMoneyHelper.openLuckyMoneyCouponIfNeed(user.getUserId(),
                LuckyMonCouponConstant.CONDITION_TYPE_ORDER_REWARD,
                userCouponRsps,true);
        luckyMoneyHelper.openLuckyMoneyCouponIfNeed(user.getUserId(),
                LuckyMonCouponConstant.CONDITION_TYPE_PAID_MONEY,
                userCouponRsps,true);
    }

    // 计算佣金
    protected BigDecimal caculateCommission(BigDecimal totalGetMoney, Double commissionRate){
        // 四舍五入
        logger.debug("totalGetMoney is : {}",totalGetMoney);
        logger.debug("commissionRate is : {}",commissionRate);
        BigDecimal bCimmissionRate = new BigDecimal(commissionRate)
                .setScale(OrdersConstant.SCALE,BigDecimal.ROUND_DOWN);
        // 除于100, 四舍五入
        bCimmissionRate = bCimmissionRate.divide(new BigDecimal("100"),BigDecimal.ROUND_DOWN)
                .setScale(OrdersConstant.SCALE,BigDecimal.ROUND_DOWN);
        logger.debug("bCimmissionRate is : {}",bCimmissionRate);
        logger.debug("userCommission is : {}",totalGetMoney.multiply(bCimmissionRate));
        // 乘于佣金比例等于用户所得佣金
        return totalGetMoney
                .multiply(bCimmissionRate)
                .setScale(OrdersConstant.SCALE,BigDecimal.ROUND_DOWN);
    }

    // 计算用户佣金，上级，上上级
    protected void countCommission(Object object,User user,Integer type,BigDecimal commissionFee,BigDecimal goodsPrice){

        UserGrade userGrade = userGradeMapper.selectByPrimaryKey(user.getUserGradeId());
        Double firstLevelCommission = userGrade.getFirstCommission();
        Double secondLevelCommission = 0.00;
        Double thirdLevelCommission = 0.00;

        if(user.getParentUserId() != null){
            User parentUser = userMapper.selectUserByUserId(user.getParentUserId());
            UserGrade ug = userGradeMapper.selectByPrimaryKey(parentUser.getUserGradeId());
            secondLevelCommission = ug.getSecondCommission();

            if (parentUser.getParentUserId() != null){
                User parentPUser = userMapper.selectById(parentUser.getParentUserId());
                UserGrade grade = userGradeMapper.selectByPrimaryKey(parentPUser.getUserGradeId());
                thirdLevelCommission = grade.getThirdCommission();
            }
        }

        // 根据用户下单价格到佣金等级表进行查找
        List<CommissionLevelSettings> commissionLevelSettingses =
                commissionLevelSettingsMapper.selectByBeginAndEnd(commissionFee);
        logger.debug("commissionLevelSettingses is : {}",commissionLevelSettingses);

        if(!ListUtil.isEmptyList(commissionLevelSettingses)){
            List<CommissionLevelSettings> st1 = commissionLevelSettingses.stream()
                    .filter(setting -> !userGrade.getId().equals(setting.getUserGradeId()))
                    .collect(Collectors.toList());
            logger.debug("st1 is : {}",st1);
            // 如果用户等级佣金比例设置开启
            if(userGrade.getEnableCmlevelSettings() == 1){
                List<CommissionLevelSettings> st2 = commissionLevelSettingses.stream()
                        .filter(setting -> userGrade.getId().equals(setting.getUserGradeId()))
                        .collect(Collectors.toList());
                logger.debug("st2 is : {}",st2);

                if(!ListUtil.isEmptyList(st2)){
                    st1 = st2;
                }
            }
            commissionLevelSettingses = st1;
        }

        // 如果佣金等级表存在多条适合条件记录（设置重叠情况），那么取第一条
        // 佣金等级表的佣金比例用户等级设置比率
        if (!ListUtil.isEmptyList(commissionLevelSettingses)){
            CommissionLevelSettings commissionLevelSettings = commissionLevelSettingses.get(0);
            firstLevelCommission = commissionLevelSettings.getRate().doubleValue();
        }

        logger.debug("one , two , three level commission rate is : {},{},{}",
                firstLevelCommission,secondLevelCommission,thirdLevelCommission);

        // 如果等级表的数据某一条为空,按照默认值设置
        firstLevelCommission = firstLevelCommission == null ? 100 : firstLevelCommission;
        secondLevelCommission = secondLevelCommission == null ? 0 : secondLevelCommission;
        thirdLevelCommission = thirdLevelCommission == null ? 0 : thirdLevelCommission;
        // 用户本人佣金
        BigDecimal userCommission =
                caculateCommission(commissionFee,firstLevelCommission);
        // 上级佣金
        BigDecimal oneLevelCommission =
                caculateCommission(commissionFee,secondLevelCommission);
        // 上上级佣金
        BigDecimal twoLevelCommission =
                caculateCommission(commissionFee,thirdLevelCommission);

        // 计算用户获取的积分宝，上级积分宝，上上级积分宝
        Long userUit = DecimalUtil.convertMoneyToUit(userCommission);
        Long oneLevelUit = DecimalUtil.convertMoneyToUit(oneLevelCommission);
        Long twoLevelUit = DecimalUtil.convertMoneyToUit(twoLevelCommission);

        if (type == 0) {
            PddOrders pddOrders = (PddOrders) object;

            if (pddOrders.getActivityId()!=null){
                // 活动订单，已计算过用户的佣金
                return;
            }
            // 用户佣金可以直接设置
            pddOrders.setUserCommission(userCommission);
            logger.debug("userCommission,oneLevelCommission,twoLevelCommission is : {},{},{}",
                    userCommission, oneLevelCommission, twoLevelCommission);
            pddOrders.setUserUit(userUit);
            if (user.getParentUserId() != null) {
                User parentUser = userMapper.selectById(user.getParentUserId());
                pddOrders.setOneLevelCommission(oneLevelCommission);
                pddOrders.setOneLevelUserUit(oneLevelUit);
                if (parentUser.getParentUserId() != null) {
                    pddOrders.setTwoLevelCommission(twoLevelCommission);
                    pddOrders.setTwoLevelUserUit(twoLevelUit);
                }
            }
        }

        if (type == 1){
            JdOrders jdOrders = (JdOrders) object;
            // 用户佣金可以直接设置
            jdOrders.setUserCommission(userCommission);
            logger.debug("userCommission,oneLevelCommission,twoLevelCommission is : {},{},{}",
                    userCommission, oneLevelCommission, twoLevelCommission);
            jdOrders.setUserUit(userUit);
            if (user.getParentUserId() != null) {
                User parentUser = userMapper.selectById(user.getParentUserId());
                jdOrders.setOneLevelCommission(oneLevelCommission);
                jdOrders.setOneLevelUserUit(oneLevelUit);
                if (parentUser.getParentUserId() != null) {
                    jdOrders.setTwoLevelCommission(twoLevelCommission);
                    jdOrders.setTwoLevelUserUit(twoLevelUit);
                }

            }
        }
        logger.debug("userUit,oneLevelUit,twoLevelUit is : {},{},{}",
                userUit,oneLevelUit,twoLevelUit);
    }

    // 判断是否是活动订单
    protected void dealwithActivityOrdersLogicIfis(PddOrders orders,PddOrders previousOrders,Long userId){

        // 活动订单已存在
        if (previousOrders != null && previousOrders.getCustomParameters() != null){
            orders.setCustomParameters(previousOrders.getCustomParameters());
            orders.setUserCommission(previousOrders.getUserCommission());
            orders.setUserUit(previousOrders.getUserUit());
            return;
        }
        // 活动商品
        if (orders.getCustomParameters().equals("activityOrders")){
            List<ActivityBrowseProduct> productList =
                    activityBrowseProductMapper.getActivityBrowseProductByUserId(orders.getGoodsId().toString(), userId);
            logger.debug("productList is : {}",productList);
            if (productList.size() > 0) {
                ActivityBrowseProduct activityBrowseProduct = productList.get(0);
                logger.debug("ActivityBrowseProduct is : {}", activityBrowseProduct);
                int activityId = activityBrowseProduct.getActivityId();
                // 0 元购活动
                if (activityId == ActivityConstant.ZERO_PURCHASE_ACTIVITY) {
                    ActivityProduct activityProduct = activityProductMapper
                            .selectProductByActivityAndProductId(activityId, String.valueOf(orders.getGoodsId()));
                    logger.debug("activityProduct is : {}",activityProduct);
                    logger.debug("activityId and goodsId is : {},{}",activityId,orders.getGoodsId());
                    if (activityProduct == null) {
                        logger.debug("now activityProduct found");
                        return;
                    }
                    // 用户实际获取金额
                    orders.setUserCommission(activityProduct.getRefundsPrice());
                    Long userUit = activityProduct.getRefundsPrice()
                            .multiply(new BigDecimal("100")).longValue();
                    orders.setUserUit(userUit);
                    // 活动订单记录
                    OrderActivityRecord orderActivityRecord = new OrderActivityRecord();
                    orderActivityRecord.setActivityId(activityId);
                    orderActivityRecord.setActivityProductId(activityProduct.getId());
                    orderActivityRecord.setCreateTime(DateUtil.getNowStr());
                    orderActivityRecord.setQualType(activityProduct.getQualType());
                    orderActivityRecord.setUserId(userId);
                    orderActivityRecord.setTradeId(orders.getOrderSn());
                    orderActivityRecordMapper.insertSelective(orderActivityRecord);
                }
                orders.setOneLevelUserUit(0L);
                orders.setTwoLevelUserUit(0L);
                orders.setOneLevelCommission(new BigDecimal("0.00"));
                orders.setTwoLevelCommission(new BigDecimal("0.00"));
                orders.setActivityId(activityId);
            }
        }
    }

}
